﻿using ComClassLibrary;
using InputUserControl;
using KeyboardArg;
using LogLib;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;

namespace InputTool
{
    public partial class FormInputTool : Form
    {
        private string m_strLogName = "InputTool";

        private static string _appDir = "";
        public static string AssemblyDirectory
        {
            get
            {
                if (string.IsNullOrEmpty(_appDir))
                {
                    Assembly ass = Assembly.GetExecutingAssembly();
                    string directory = Path.GetDirectoryName(ass.CodeBase);
                    _appDir = directory.Substring(6);
                }
                return _appDir;
            }
        }

        private INPUT_TOOL m_toolType = INPUT_TOOL.TOOL_SMALL_CHAR;

        private Button[] m_BtnTypes = new Button[5];

        private string m_iniFile = AppDomain.CurrentDomain.BaseDirectory + "InputTool_Config.ini";

        private INIClass m_iniClass = null;

        private KeyBoardArgs _keyboardArg = new KeyBoardArgs();

        public KeyBoardArgs KeyboardArgs
        {
            get { return _keyboardArg; }
        }

        private string _keyboardArgKey = string.Empty;
        private int _retryCount = 0;
        /// <summary>
        /// 窗口隐藏事件
        /// </summary>
        public event EventHandler Hidden;
        protected void OnWndHidden()
        {
            if (Hidden != null)
            {
                Hidden(this, new EventArgs());
            }
        }

        public FormInputTool()
        {
            InitializeComponent();
            this.Load += new EventHandler(frmMain_Load);
            this.Opacity = 100;
            this.Shown += new EventHandler(frmMain_Shown);
            this.ucHandWrite.ERecognizer += new UCHandWrite.DRecognizer(ucHandWrite_ERecognizer);
            this.ucKeyBoard.EButtonClick += new UCKeyBoard.DButtonClick(ucKeyBoard_EButtonClick);
            this.panel_Title.Visible = true;
            this.panel_HandWrite.Visible = false;
            this.panel_KeyBoard.Visible = true;
            btnBigChar.Visible = true;//DataDeal.IsShowDigitalInput();
            btnSmallChar.Visible = true;// DataDeal.IsShowDigitalInput();            
        }

        public FormInputTool(KeyBoardArgs keyboardArg) : this()
        {
            SetInputToolArg(keyboardArg);
        }
        public void SetLocation(Rectangle rect)
        {
            // 计算窗体在屏幕上的位置，使其位于屏幕中心
            int x = rect.Left + (rect.Width - Width) / 2;
            int y = rect.Top + (rect.Height - Height) / 2;

            // 设置窗体的位置
            Location = new Point(x, y);
        }
        public void SetInputToolArg(KeyBoardArgs args)
        {
            if (args == null)
            {
                return;
            }
            _keyboardArg = args;
            lblTitle.Text = _keyboardArg.Title;
            tbInput.MaxLength = _keyboardArg.MaxLength;
            tbInput.Text = _keyboardArg.Content;
            _keyboardArgKey = _keyboardArg.Key;
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            string strClass = System.Reflection.MethodBase.GetCurrentMethod().Name;
            string strLog = "In";
            XDLog.WriteLog(m_strLogName, strClass, strLog);
            try
            {
                m_BtnTypes[0] = btnShouXie;
                m_BtnTypes[1] = btnPinYin;
                m_BtnTypes[2] = btnWuBi;
                m_BtnTypes[3] = btnBigChar;
                m_BtnTypes[4] = btnSmallChar;

                //modify by lt 20161213
                strLog = string.Format("tbInput.MaxLength：[{0}]", tbInput.MaxLength.ToString());
                XDLog.WriteLog(m_strLogName, strClass, strLog);

                m_iniClass = new INIClass(m_iniFile);
                foreach (InputLanguage inputLanguage in InputLanguage.InstalledInputLanguages)
                {
                    if (inputLanguage.LayoutName.Contains("搜狗拼音"))//cyy
                    {
                        m_iniClass.IniWriteValue("InputTool", "PinYin_Name", inputLanguage.LayoutName);
                    }
                    else if (inputLanguage.LayoutName.Contains("五笔"))
                    {
                        m_iniClass.IniWriteValue("InputTool", "WuBi_Name", inputLanguage.LayoutName);
                    }
                    else if (inputLanguage.LayoutName.Contains("极品"))
                    {
                        m_iniClass.IniWriteValue("InputTool", "WuBi_Name", inputLanguage.LayoutName);
                    }
                    strLog = string.Format("InstalledInputLanguages：[{0}]", inputLanguage.LayoutName);
                    XDLog.WriteLog(m_strLogName, strClass, strLog);
                }
                //if (DataDeal.IsTest())
                //{
                //    timerTest.Enabled = true;
                //}
                InitImages();
                ShowPageDownUpCtrl(false);
                btnShouXie.PerformClick();
            }
            catch (Exception ex)
            {
                strLog = ex.Message;
                XDLog.WriteLog(m_strLogName, strClass, strLog);
                ShowMessageBoxError(strLog, strClass);
            }
            strLog = "Out";
            XDLog.WriteLog(m_strLogName, strClass, strLog);
        }

        private void InitImages()
        {
            string strClass = System.Reflection.MethodBase.GetCurrentMethod().Name;
            string strLog = "In";
            XDLog.WriteLog(m_strLogName, strClass, strLog);
            try
            {
                string strImageDir = Path.Combine(AssemblyDirectory, "Images");
                string strBkgndImg = strImageDir + "\\BackgroundImage.png";
                string strConfirmImg = strImageDir + "\\Confirm.png";
                string strBkspaceImg = strImageDir + "\\Backspace.png";
                string strHandWriteImg = strImageDir + "\\ShouXie.png";
                string strWuBiImg = strImageDir + "\\WuBi.png";
                string strPinYinImg = strImageDir + "\\PinYin.png";
                string strBigChar = strImageDir + "\\BigChar.png";
                string strSmallChar = strImageDir + "\\SmallChar.png";

                string strPageDown = strImageDir + "\\PageDown.png";
                string strPageUp = strImageDir + "\\PageUp.png";
                string strClose = strImageDir + "\\Close.png";

                string[] InputTypeImage = new string[5];
                InputTypeImage[0] = strHandWriteImg;
                InputTypeImage[1] = strWuBiImg;
                InputTypeImage[2] = strPinYinImg;
                InputTypeImage[3] = strBigChar;
                InputTypeImage[4] = strSmallChar;

                if (File.Exists(strBkgndImg))
                {
                    this.BackgroundImage = new Bitmap(strBkgndImg);
                    this.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
                }
                if (File.Exists(strClose))
                {
                    this.buttonCancel.BackgroundImage = new Bitmap(strClose);
                    this.buttonCancel.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
                }

                if (File.Exists(strConfirmImg))
                {
                    this.btnConfirm.BackgroundImage = new Bitmap(strConfirmImg);
                    this.btnConfirm.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
                }

                if (File.Exists(strBkspaceImg))
                {
                    this.btnBackspace.BackgroundImage = new Bitmap(strBkspaceImg);
                    this.btnBackspace.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
                }
                for (int nIndex = 0; nIndex < m_BtnTypes.Length; nIndex++)
                {
                    if (File.Exists(InputTypeImage[nIndex]))
                    {
                        this.m_BtnTypes[nIndex].BackgroundImage = new Bitmap(InputTypeImage[nIndex]);
                        this.m_BtnTypes[nIndex].BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
                    }
                }

                if (File.Exists(strPageDown))
                {
                    this.btnPageDown.BackgroundImage = new Bitmap(strPageDown);
                    this.btnPageDown.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
                }
                if (File.Exists(strPageUp))
                {
                    this.btnPageUp.BackgroundImage = new Bitmap(strPageUp);
                    this.btnPageUp.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
                }

            }
            catch (Exception ex)
            {
                strLog = ex.Message;
                XDLog.WriteLog(m_strLogName, strClass, strLog);
                ShowMessageBoxError(strLog, strClass);
            }
            strLog = "Out";
            XDLog.WriteLog(m_strLogName, strClass, strLog);
        }

        private void UpdateToolState()
        {
            string strClass = System.Reflection.MethodBase.GetCurrentMethod().Name;
            string strLog = "In";
            XDLog.WriteLog(m_strLogName, strClass, strLog);
            try
            {
                int nIndex = (int)m_toolType;
                if (nIndex < m_BtnTypes.Length)
                {
                    for (int btnIndex = 0; btnIndex < m_BtnTypes.Length; btnIndex++)
                    {
                        if (btnIndex == nIndex)
                        {
                            m_BtnTypes[btnIndex].Enabled = false;
                        }
                        else
                        {
                            m_BtnTypes[btnIndex].Enabled = true;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                strLog = ex.Message;
                XDLog.WriteLog(m_strLogName, strClass, strLog);
                ShowMessageBoxError(strLog, strClass);
            }
            strLog = "Out";
            XDLog.WriteLog(m_strLogName, strClass, strLog);
        }

        private void UpdatePanelState()
        {
            string strClass = System.Reflection.MethodBase.GetCurrentMethod().Name;
            string strLog = "In";
            XDLog.WriteLog(m_strLogName, strClass, strLog);
            try
            {
                if (m_toolType == INPUT_TOOL.TOOL_SHOUXIE)
                {
                    panel_HandWrite.Visible = true;
                    panel_KeyBoard.Visible = false;
                }
                else
                {
                    panel_HandWrite.Visible = false;
                    panel_KeyBoard.Visible = true;
                }

            }
            catch (Exception ex)
            {
                strLog = ex.Message;
                XDLog.WriteLog(m_strLogName, strClass, strLog);
                ShowMessageBoxError(strLog, strClass);
            }
            strLog = "Out";
            XDLog.WriteLog(m_strLogName, strClass, strLog);
        }

        private void frmMain_Shown(object sender, EventArgs e)
        {
            string strClass = System.Reflection.MethodBase.GetCurrentMethod().Name;
            string strLog = "In";
            XDLog.WriteLog(m_strLogName, strClass, strLog);
            try
            {
                m_toolType = INPUT_TOOL.TOOL_SHOUXIE;//cyy
                UpdateToolState();
                UpdatePanelState();
                //m_toolType = ucKeyBoard.InputTool;//cyy
                tbInput.Select(tbInput.Text.Length, 0);
                tbInput.Focus();
            }
            catch (Exception ex)
            {
                strLog = ex.Message;
                XDLog.WriteLog(m_strLogName, strClass, strLog);
                ShowMessageBoxError(strLog, strClass);
            }
            strLog = "Out";
            XDLog.WriteLog(m_strLogName, strClass, strLog);
        }


        private void InputBox_Focus()
        {
            int nSelIndex = tbInput.SelectionStart;
            if (nSelIndex <= 0)
            {
                tbInput.Select(tbInput.Text.Length, 0);
            }
            else
            {
                tbInput.Select(tbInput.SelectionStart, 0);
            }
            tbInput.Focus();
        }

        private void ucKeyBoard_EButtonClick(string strClickText)
        {
            string strClass = System.Reflection.MethodBase.GetCurrentMethod().Name;
            string strLog = "In";
            XDLog.WriteLog(m_strLogName, strClass, strLog);
            try
            {
                InputBox_Focus();
                if (m_toolType == INPUT_TOOL.TOOL_PINYIN || m_toolType == INPUT_TOOL.TOOL_WUBI)
                {
                    if (strClickText == "-" || strClickText == "#")
                    {
                        //modify by lt 20161213
                        if (tbInput.Text.Length >= _keyboardArg.MaxLength) return;
                        tbInput.Text += strClickText;
                    }
                    else if (strClickText.Length > 0)
                    {
                        InputBox_Focus();
                        byte btKey = (Byte)strClickText[0];
                        Library.keybd_event(btKey, 0, 0, 0);
                        Library.keybd_event(btKey, 0, 2, 0);
                    }
                }
                else
                {
                    //modify by lt 20161213
                    if (tbInput.Text.Length >= _keyboardArg.MaxLength) return;
                    tbInput.Text = tbInput.Text + strClickText;
                }
                InputBox_Focus();
            }
            catch (Exception ex)
            {
                strLog = ex.Message;
                XDLog.WriteLog(m_strLogName, strClass, strLog);
                ShowMessageBoxError(strLog, strClass);
            }
            strLog = "Out";
            XDLog.WriteLog(m_strLogName, strClass, strLog);
        }

        private void ucHandWrite_ERecognizer(string strRecText)
        {
            string strClass = System.Reflection.MethodBase.GetCurrentMethod().Name;
            string strLog = "In";
            XDLog.WriteLog(m_strLogName, strClass, strLog);
            try
            {
                string[][] strReplaceChar = new string[4][];
                strReplaceChar[0] = new string[] { "/", ",", "'", "’", "′", "‘", ".", "\"" };
                strReplaceChar[1] = new string[] { "\\", "丶", "‵", "`", "、", "·", ".", "‘", "\"" };
                strReplaceChar[2] = new string[] { "〉", "丿", "「", "丶", "、", "'", ">〉", "乛", "」" };
                strReplaceChar[3] = new string[] { "∴", ":", "〃", ")", "|", "〃", "‐", "_" };

                for (int nX = 0; nX < strReplaceChar.Length; nX++)
                {
                    for (int nY = 0; nY < strReplaceChar[nX].Length; nY++)
                    {
                        string strTmp = strRecText.Replace(strReplaceChar[nX][nY], "");
                        strRecText = strTmp;
                    }
                }
                //modify by lt 20161213
                strLog = "In-test";
                XDLog.WriteLog(m_strLogName, strClass, strLog);

                if (tbInput.Text.Length >= _keyboardArg.MaxLength)
                {
                    XDLog.WriteLog(m_strLogName, strClass, string.Format("tbInput的长度为{0}:::{1}", tbInput.Text.Length, _keyboardArg.MaxLength));
                    strLog = "In-test111";
                    XDLog.WriteLog(m_strLogName, strClass, strLog);
                    return;
                }
                tbInput.Text = tbInput.Text + strRecText;
            }
            catch (Exception ex)
            {
                strLog = ex.Message;
                XDLog.WriteLog(m_strLogName, strClass, strLog);
                ShowMessageBoxError(strLog, strClass);
            }
            strLog = "Out";
            XDLog.WriteLog(m_strLogName, strClass, strLog);
        }

        private bool ChangeInputMode(INPUT_TOOL toolType, ref string ErrMsg)
        {
            bool bOK = false;
            string strClass = System.Reflection.MethodBase.GetCurrentMethod().Name;
            string strLog = "In";
            string strInputName = "";
            XDLog.WriteLog(m_strLogName, strClass, strLog);
            try
            {
                if (toolType == INPUT_TOOL.TOOL_WUBI)
                {
                    strInputName = m_iniClass.IniReadValue("InputTool", "WuBi_Name");
                }
                if (toolType == INPUT_TOOL.TOOL_PINYIN)
                {
                    strInputName = m_iniClass.IniReadValue("InputTool", "PinYin_Name");
                }
                if (toolType == INPUT_TOOL.TOOL_BIG_CHAR || toolType == INPUT_TOOL.TOOL_SMALL_CHAR)
                {
                    //strInputName = "中文(简体) - 美式键盘";
                    strInputName = "美式键盘";
                }
                foreach (InputLanguage inputLanguage in InputLanguage.InstalledInputLanguages)
                {
                    if (inputLanguage.LayoutName.Contains(strInputName))
                    {
                        bOK = true;
                        InputBox_Focus();
                        InputLanguage.CurrentInputLanguage = inputLanguage;
                        break;
                    }
                }
                if (!bOK)
                {
                    ErrMsg = string.Format("没有找到输入法：[{0}]\r\n\r\n请检查电脑上是否已安装该输入法！", strInputName);
                    XDLog.WriteLog(m_strLogName, strClass, ErrMsg);
                }
            }
            catch (Exception ex)
            {
                bOK = false;
                strLog = ex.Message;
                XDLog.WriteLog(m_strLogName, strClass, strLog);
            }
            strLog = "Out";
            XDLog.WriteLog(m_strLogName, strClass, strLog);
            return bOK;

        }

        private void ShowPageDownUpCtrl(bool bShow)
        {
            btnPageDown.Visible = bShow;
            btnPageUp.Visible = bShow;
        }

        private void InputType_ButtonClick(object sender, EventArgs e)
        {
            string strClass = System.Reflection.MethodBase.GetCurrentMethod().Name;
            string strLog = "In";
            XDLog.WriteLog(m_strLogName, strClass, strLog);
            try
            {
                if (m_toolType == INPUT_TOOL.TOOL_SHOUXIE)
                {
                    if (null != _ucCompany)
                    {
                        ucHandWrite.Visible = true;
                        _ucCompany.Visible = false;
                        panel_HandWrite.Controls.Remove(_ucCompany);
                    }
                }
                else
                {
                    if (null != _ucCompany)
                    {
                        _ucCompany.Visible = false;
                        panel_KeyBoard.Controls.Remove(_ucCompany);
                        ucKeyBoard.Visible = true;
                    }
                }
                Button btn = sender as Button;
                if (btn != null)
                {
                    int nIndex = 0;
                    for (int btnIndex = 0; btnIndex < m_BtnTypes.Length; btnIndex++)
                    {
                        if (m_BtnTypes[btnIndex].Name == btn.Name)
                        {
                            nIndex = btnIndex;
                            break;
                        }
                    }
                    ShowPageDownUpCtrl(false);
                    INPUT_TOOL toolType = (INPUT_TOOL)nIndex;
                    if (!ChangeInputMode(toolType, ref strLog))
                    {
                        ShowMessageBoxWarning(strLog, "警告");
                        return;
                    }
                    if (toolType == INPUT_TOOL.TOOL_PINYIN)
                    {
                        ShowPageDownUpCtrl(true);
                    }

                    ucKeyBoard.InputTool = toolType;
                    m_toolType = toolType;
                    UpdateToolState();
                    UpdatePanelState();
                }
            }
            catch (Exception ex)
            {
                strLog = ex.Message;
                XDLog.WriteLog(m_strLogName, strClass, strLog);
                ShowMessageBoxError(strLog, strClass);
            }
            strLog = "Out";
            XDLog.WriteLog(m_strLogName, strClass, strLog);
        }

        #region 消息框


        private void ShowMessageBoxError(string MsgText, string Title)
        {
            MessageBox.Show(MsgText, Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        private void ShowMessageBoxWarning(string MsgText, string Title)
        {
            MessageBox.Show(MsgText, Title, MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }

        private void ShowMessageBoxOK(string MsgText, string Title)
        {
            MessageBox.Show(MsgText, Title, MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        #endregion

        private void btnBackspace_Click(object sender, EventArgs e)
        {
            string strClass = System.Reflection.MethodBase.GetCurrentMethod().Name;
            string strLog = "btnBackspace_Click In";
            XDLog.WriteLog(m_strLogName, strClass, strLog);
            try
            {
                XDLog.WriteLog(m_strLogName, strClass, $"原有字符：{strInput}");
                if (m_toolType == INPUT_TOOL.TOOL_SHOUXIE)
                {
                    if (null != _ucCompany)
                    {
                        ucHandWrite.Visible = true;
                        _ucCompany.Visible = false;
                        panel_HandWrite.Controls.Remove(_ucCompany);
                    }
                }
                else
                {
                    if (null != _ucCompany)
                    {
                        _ucCompany.Visible = false;
                        panel_KeyBoard.Controls.Remove(_ucCompany);
                        ucKeyBoard.Visible = true;
                    }
                }

                strInput = tbInput.Text;
                if (strInput.Length > 0)
                {
                    strInput = strInput.Remove(strInput.Length - 1);
                    XDLog.WriteLog(m_strLogName, strClass, $"现有字符：{strInput}");
                }
                else
                {
                    XDLog.WriteLog(m_strLogName, strClass, $"字符长度为0");
                }
                tbInput.Text = strInput;
                XDLog.WriteLog(m_strLogName, strClass, $"显示字符：{tbInput.Text}");
                //InputBox_Focus();
                //Library.keybd_event(0x008, 0, 0, 0);
                //Library.keybd_event(0x008, 0, 2, 0);

            }
            catch (Exception ex)
            {
                strLog = ex.Message;
                XDLog.WriteLog(m_strLogName, strClass, strLog);
                ShowMessageBoxError(strLog, strClass);
            }
            strLog = "btnBackspace_Click Out";
            XDLog.WriteLog(m_strLogName, strClass, strLog);
        }

        private void GetCompany()
        {
            DateTime start = DateTime.Now;
            TimeSpan ts = new TimeSpan();
            while (!Company._isClickCompany && ts.Minutes < 1)
            {
                //if (_isNewQuery)
                //{
                //    return;
                //}
                Thread.Sleep(10);
                DateTime end = DateTime.Now;
                ts = end - start;
            }
            Company._isClickCompany = false;
            _keyboardArg.PassageType = SendMessageType.Response;
            _keyboardArg.Content = string.IsNullOrEmpty(Company._selectName) ? strInput : Company._selectName;
            SendMessage();
            _retryCount = 0;
            Company._selectName = string.Empty;
            Action atTime = new Action(() =>
            {
                _ucCompany.Visible = false;
                if (m_toolType == INPUT_TOOL.TOOL_SHOUXIE)
                {
                    ucHandWrite.Visible = true;
                }
                else
                {
                    ucKeyBoard.Visible = true;
                }

                this.Hide();
                OnWndHidden();
            });
            this.BeginInvoke(atTime);
        }
        string strInput = "";
        ucCompany _ucCompany = null;
        Thread _thGetCompany = null;
        bool _isNewQuery = false;
        private void btnConfirm_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(tbInput.Text))
                {
                    return;
                }
                strInput = tbInput.Text.Trim();
                if (_keyboardArgKey == "DWDZ")
                {
                    _isNewQuery = true;
                    lblTitle.Text = "正在查询企业信息，请稍候。。。";
                    picWaiting.Visible = true;
                    if (m_toolType == INPUT_TOOL.TOOL_SHOUXIE)
                    {
                        if (null != _ucCompany)
                        {
                            panel_HandWrite.Controls.Remove(_ucCompany);
                        }
                    }
                    else
                    {
                        if (null != _ucCompany)
                        {
                            panel_KeyBoard.Controls.Remove(_ucCompany);
                        }
                    }
                    string err = string.Empty;
                    Company._names = null;
                    Company._selectName = string.Empty;
                    List<string> names = new List<string>();
                    string url = IniFile.IniValue("GetCompanyWebApi", "url", "", "");
                    Thread th = new Thread(
                () =>
                {
                    names = HttpCompany.HttpPost(url, strInput, ref err);
                    Action at1 = new Action(() =>
                    {
                        picWaiting.Visible = false;

                    });
                    this.Invoke(at1);
                    if (names.Count <= 0)
                    {
                        if (_retryCount >= 2)
                        {
                            _keyboardArg.PassageType = SendMessageType.Response;
                            _keyboardArg.Content = strInput;
                            _keyboardArg.Command = "OK";
                            SendMessage();
                            _retryCount = 0;
                            Action at2 = new Action(() =>
                            {
                                this.Hide();
                                OnWndHidden();

                            });
                            this.Invoke(at2);
                        }
                        else
                        {
                            Action at2 = new Action(() =>
                            {
                                lblTitle.Text = "查询<" + strInput + ">单位失败，请输入完整的单位名称";
                            });
                            this.Invoke(at2);
                            _retryCount++;
                        }
                        return;
                    }
                    _ucCompany = new ucCompany(names);

                    Action at3 = new Action(() =>
                    {
                        if (m_toolType == INPUT_TOOL.TOOL_SHOUXIE)
                        {
                            ucHandWrite.Visible = false;
                            panel_HandWrite.Controls.Add(_ucCompany);
                        }
                        else
                        {
                            ucKeyBoard.Visible = false;
                            panel_KeyBoard.Controls.Add(_ucCompany);
                        }
                        lblTitle.Text = "企业信息查询成功，请选择您所在的企业名称";
                    });
                    this.Invoke(at3);

                    GetCompany();


                });
                    th.IsBackground = true;
                    th.Start();
                }
                else
                {
                    _keyboardArg.PassageType = SendMessageType.Response;
                    _keyboardArg.Content = strInput;
                    _keyboardArg.Command = "OK";
                    SendMessage();
                    this.Hide();
                    OnWndHidden();
                }
            }
            catch (Exception ex)
            {
                picWaiting.Visible = false;
                Log.WriteException(ex.ToString());
            }
        }

        private void frmMain_InputLanguageChanged(object sender, InputLanguageChangedEventArgs e)
        {
            string strClass = System.Reflection.MethodBase.GetCurrentMethod().Name;
            string strLog = "In";
            XDLog.WriteLog(m_strLogName, strClass, strLog);
            try
            {
                Application.CurrentInputLanguage = e.InputLanguage;
            }
            catch (Exception ex)
            {
                strLog = ex.Message;
                XDLog.WriteLog(m_strLogName, strClass, strLog);
                ShowMessageBoxError(strLog, strClass);
            }
            strLog = "Out";
            XDLog.WriteLog(m_strLogName, strClass, strLog);
        }

        private void timerTest_Tick(object sender, EventArgs e)
        {
            try
            {
                string strErrMsg = "";
                if (m_toolType == INPUT_TOOL.TOOL_SHOUXIE || m_toolType == INPUT_TOOL.TOOL_BIG_CHAR
                    || m_toolType == INPUT_TOOL.TOOL_SMALL_CHAR)
                {
                    this.timerTest.Enabled = false;
                    m_toolType = INPUT_TOOL.TOOL_PINYIN;
                    ChangeInputMode(m_toolType, ref strErrMsg);
                    ucKeyBoard.InputTool = m_toolType;
                    this.timerTest.Interval = 100;
                    this.timerTest.Enabled = true;
                }
                else if (m_toolType == INPUT_TOOL.TOOL_PINYIN)
                {
                    this.timerTest.Enabled = false;
                    m_toolType = INPUT_TOOL.TOOL_WUBI;
                    ChangeInputMode(m_toolType, ref strErrMsg);
                    ucKeyBoard.InputTool = m_toolType;
                    this.timerTest.Interval = 100;
                    this.timerTest.Enabled = true;
                }
                else if (m_toolType == INPUT_TOOL.TOOL_WUBI)
                {
                    this.timerTest.Enabled = false;
                    this.Close();
                }
            }
            catch (Exception ex)
            {

            }
        }

        private void btnPageDown_Click(object sender, EventArgs e)
        {
            string strClass = System.Reflection.MethodBase.GetCurrentMethod().Name;
            string strLog = "In";
            XDLog.WriteLog(m_strLogName, strClass, strLog);
            try
            {
                InputBox_Focus();
                byte btKey = 34;
                Library.keybd_event(btKey, 0, 0, 0);
                Library.keybd_event(btKey, 0, 2, 0);

                //Library.SendMessage(tbInput.Handle, 0x0100, btKey, 5);
                //Library.SendMessage(tbInput.Handle, 0x0101, btKey, 5);
                //SendKeys.SendWait("{PGDN}");
            }
            catch (Exception ex)
            {
                strLog = ex.Message;
                XDLog.WriteLog(m_strLogName, strClass, strLog);
                ShowMessageBoxError(strLog, strClass);
            }
            strLog = "Out";
            XDLog.WriteLog(m_strLogName, strClass, strLog);
        }

        private void btnPageUp_Click(object sender, EventArgs e)
        {
            string strClass = System.Reflection.MethodBase.GetCurrentMethod().Name;
            string strLog = "In";
            XDLog.WriteLog(m_strLogName, strClass, strLog);
            try
            {
                InputBox_Focus();
                byte btKey = 33;
                Library.keybd_event(btKey, 0, 0, 0);
                Library.keybd_event(btKey, 0, 2, 0);

                //Library.SendMessage(tbInput.Handle, 0x0100, btKey,5);
                //Library.SendMessage(tbInput.Handle, 0x0101, btKey,5);
                //SendKeys.SendWait("{PGUP}");

            }
            catch (Exception ex)
            {
                strLog = ex.Message;
                XDLog.WriteLog(m_strLogName, strClass, strLog);
                ShowMessageBoxError(strLog, strClass);
            }
            strLog = "Out";
            XDLog.WriteLog(m_strLogName, strClass, strLog);
        }

        private bool SendMessage()
        {
            if (_keyboardArg.MsgReceiver == IntPtr.Zero)
            {
                MessageBox.Show("句柄错误", "句柄错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }
            int uMsg = (int)MessageType.WM_COPYDATA;
            string strMsgText = JsonHandler.ConvertToJsonString(_keyboardArg);
            byte[] data = System.Text.Encoding.UTF8.GetBytes(strMsgText);
            COPYDATASTRUCT_INTPTR cds = new COPYDATASTRUCT_INTPTR();
            cds.dwData = (IntPtr)uMsg;
            cds.cbData = data.Length;
            cds.lpData = Marshal.AllocHGlobal(data.Length);
            Marshal.Copy(data, 0, cds.lpData, data.Length);
            ComClassLibrary.Message.SendMessage(_keyboardArg.MsgReceiver, uMsg, 0, ref cds);
            return true;
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            if (_keyboardArg == null || _keyboardArg.MsgReceiver == IntPtr.Zero)
            {
                this.Hide();
                OnWndHidden();
                return;
            }
            _keyboardArg.Content = "";
            _keyboardArg.Command = "Cancel";
            int uMsg = (int)MessageType.WM_COPYDATA;
            string strMsgText = JsonHandler.ConvertToJsonString(_keyboardArg);
            byte[] data = System.Text.Encoding.UTF8.GetBytes(strMsgText);
            COPYDATASTRUCT_INTPTR cds = new COPYDATASTRUCT_INTPTR();
            cds.dwData = (IntPtr)uMsg;
            cds.cbData = data.Length;
            cds.lpData = Marshal.AllocHGlobal(data.Length);
            Marshal.Copy(data, 0, cds.lpData, data.Length);
            ComClassLibrary.Message.SendMessage(_keyboardArg.MsgReceiver, uMsg, 0, ref cds);
            this.Hide();
            OnWndHidden();
        }

        private void FormInputTool_Load(object sender, EventArgs e)
        {
            //Thread.CurrentThread.CurrentCulture = new CultureInfo("ar-SA");
            int scrWidth = Screen.PrimaryScreen.Bounds.Width;
            int scrHeight = Screen.PrimaryScreen.Bounds.Height;
            int x = (scrWidth - this.Width) / 2;
            int y = (scrHeight - this.Height) - 200;
            //this.Location = new Point(x, y);
        }
    }
}